import { Outlet, useNavigate, useLocation, useRoutes  } from 'react-router'
import { useEffect, useState } from 'react'
import { Spin } from 'antd'
import { getLocalStorage } from 'packages/shared/utils/storage'
import { allRoutes } from '@/router'

const AuthMiddleware = () => {
  const [login, setLogin] = useState(false)
  const navigate = useNavigate()
  const location = useLocation()
  const routes = allRoutes()
  const  user = getLocalStorage('user', true)
  useEffect(() => {
    if(user?.token){
      const currentRoute = routes.find((item) => item.path === location.pathname)
      setLogin(true)
      if(location.pathname === '/'){
        navigate('/home')
      }
      if(currentRoute?.roles){
        const hasPermission = currentRoute.roles?.includes(user.role)
        if(!hasPermission){
          navigate('/401')
        }
      }
    } else {
      // 未登录，跳转到登录页
      navigate('/login')
    }
  }, [])
  return login ? <Outlet /> : <Spin spinning />
}

export default AuthMiddleware
